package legway;

import java.io.*;
import lejos.nxt.LCD;
import lejos.nxt.comm.*;
/**
 * Reads new commands from the computer 
 * 
 * @author Kim Petersen, Andreas Koefoed-Hansen og Tim Rasmussen
 * @version Januar 2010
 */
public class BTCommandReader extends Thread
{
	DataInputStream istream;
	private int command;
	private BTConnection conn;
	private Thread driverThread;

	/**
	 * BTCommandReader constructor.
	 * 
	 * @param conn The Bluetooth Connection set up with the Legway
	 */
	public BTCommandReader(BTConnection conn, Thread driverThread) {
		this.conn = conn;
		this.driverThread = driverThread;
		istream = conn.openDataInputStream();
	}

	/**
	 * BTCommandReader thread which constantly runs waiting for new commands
	 */
	public void run() {
		command = 0;
		try {
			while (true) {
				command = istream.readInt();
				//LCD.drawInt(command, 0, 0);
				try {Thread.sleep(100);} catch (InterruptedException e) {}
			}
		} catch (Exception e) { //Connection lost, notify driver
			driverThread.interrupt();
			// Clean up
			try {
				if(istream != null)
					istream.close();
				if(conn != null)
					conn.close();
			} catch (IOException e1) { }
		}
	}

	/**
	 * Reutrns the current commands send over Bluetooth
	 * @return the current command sent over Bluetooth
	 */
	public int getCommand() { return command; }

}